package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.PublishConstants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.system.domain.PArticle;
import com.ruoyi.system.domain.bo.PArticleBo;
import com.ruoyi.system.domain.vo.PArticleVo;
import com.ruoyi.system.mapper.PArticleMapper;
import com.ruoyi.system.service.IPArticleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 心理咨询文章Service业务层处理
 *
 * @author ruoyi
 * @date 2022-07-28
 */
@RequiredArgsConstructor
@Service
public class PArticleServiceImpl implements IPArticleService {

    private final PArticleMapper baseMapper;

    /**
     * 查询心理咨询文章
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PArticleVo queryById(Long id){
        PArticleVo articleVo = baseMapper.selectVoById(id);
        if (ObjectUtil.isEmpty(articleVo)) {
            throw new ServiceException("非法数据！");
        }

        Long userId = LoginHelper.getUserId();
        String readKey = PublishConstants.ARTICLE_READ_KEY + userId;
        // 设置每个用户一天只浏览一次
        if (!RedisUtils.hasKey(readKey)) {
            RedisUtils.setCacheObject(readKey, 1, Duration.ofDays(1));
            PArticle article = new PArticle();
            article.setId(article.getId());
            article.setReadNum(articleVo.getReadNum() + 1);
            baseMapper.updateById(article);
            // 返回更新的阅读量
            articleVo.setReadNum(articleVo.getReadNum() + 1);
            return articleVo;
        }

        return articleVo;
    }

    /**
     * 查询心理咨询文章列表
     */
    @Override
    public TableDataInfo<PArticleVo> queryPageList(PArticleBo bo, PageQuery pageQuery) {
        QueryWrapper<PArticle> lqw = Wrappers.query();
        lqw.like(StringUtils.isNotBlank(bo.getTitle()), "a.title", bo.getTitle());
        lqw.like(StringUtils.isNotBlank(bo.getUsername()), "u.username", bo.getUsername());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), "a.status", bo.getStatus());
        lqw.eq(bo.getCategoryId() != null, "a.category_id", bo.getCategoryId());
        Page<PArticleVo> result = baseMapper.selectMyVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询心理咨询文章列表
     */
    @Override
    public List<PArticleVo> queryList(PArticleBo bo) {
        LambdaQueryWrapper<PArticle> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PArticle> buildQueryWrapper(PArticleBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PArticle> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), PArticle::getTitle, bo.getTitle());
        lqw.eq(bo.getUserId() != null, PArticle::getUserId, bo.getUserId());
        lqw.eq(bo.getReadNum() != null, PArticle::getReadNum, bo.getReadNum());
        lqw.eq(StringUtils.isNotBlank(bo.getInfo()), PArticle::getInfo, bo.getInfo());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), PArticle::getStatus, bo.getStatus());
        lqw.eq(bo.getCategoryId() != null, PArticle::getCategoryId, bo.getCategoryId());
        return lqw;
    }

    /**
     * 新增心理咨询文章
     */
    @Override
    public Boolean insertByBo(PArticleBo bo) {
        PArticle add = BeanUtil.toBean(bo, PArticle.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改心理咨询文章
     */
    @Override
    public Boolean updateByBo(PArticleBo bo) {
        PArticle update = BeanUtil.toBean(bo, PArticle.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PArticle entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除心理咨询文章
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void insertFontByBo(PArticleBo bo) {
        PArticle add = BeanUtil.toBean(bo, PArticle.class);
        add.setUserId(LoginHelper.getUserId());
        add.setStatus(PublishConstants.COMMON_NO);
        baseMapper.insert(add);
    }

    @Override
    public TableDataInfo<PArticleVo> queryLeftPageList(PArticleBo bo, PageQuery pageQuery) {
        QueryWrapper<PArticle> lqw = Wrappers.query();
        lqw.eq(bo.getUserId() != null, "a.user_id", bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), "a.status", bo.getStatus());
        lqw.eq(bo.getCategoryId() != null, "a.category_id", bo.getCategoryId());
        Page<PArticleVo> result = baseMapper.selectLeftVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }
}
